<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="btn1">开始</button>
  <button id="btn2">停止</button>
  <video width="120" height="90" autoplay controls id="video"></video>
</body>
<script>
  "use strict"; {
    let btn1 = document.getElementById("btn1");
    let btn2 = document.getElementById("btn2");
    let video = document.getElementById("video");
    let mediaRecorders = null, stream = null, blobs = [];
    // 点击开始按钮
    btn1.addEventListener("click", async () => {

      stream = await navigator.mediaDevices.getUserMedia({ video: false, audio: true });
      if (mediaRecorders) return void 0; //有值时不做任何操作了
      mediaRecorders = new MediaRecorder(stream); //创建录音对象
      // 监听到录音对象有数据时，就开始打印
      mediaRecorders.addEventListener("dataavailable", res => {
        console.log(res.data);
        blobs.push(res.data);
      });
      mediaRecorders.start(1000); //开始录音了
    });

    // 点击停止按钮
    btn2.addEventListener("click", () => {
      // 当录音对象已经存在时，才进行操作(停止录音/清空对象)
      if (!mediaRecorders) return void 0;
      console.log(`停止了`);
      mediaRecorders.stop();
      mediaRecorders = stream = null;
      // 当录制到声音后，播放声音
      if (!blobs.length) return void 0;
      let allData = new Blob(blobs);
      video.src = URL.createObjectURL(allData);
    });
  };
</script>

</html>